//
//  ViewController.m
//  OpensslTest
//
//  Created by jiahua on 16/3/23.
//  Copyright © 2016年 secsmarts. All rights reserved.
//

#import "ViewController.h"
#import "sstNSStringFormat.h"
#import "sstNSDataFormat.h"
#import "HttpClient.h"
#import "KeyManage.h"
#import "SSTInitFactory.h"
#import "DeviceManager.h"
#import "GCDUtil.h"

static NSMutableDictionary* errorTagEncode;

@interface ViewController ()
{
}
@property (weak, nonatomic) IBOutlet UITextField *ipText;
@property (weak, nonatomic) IBOutlet UITextField *tcpPort;
@property (weak, nonatomic) IBOutlet UIButton *tcpConnectButton;
@property (weak, nonatomic) IBOutlet UILabel *tcpInfoLabel;
@property (weak, nonatomic) IBOutlet UILabel *tcpInfo;

@property (weak, nonatomic) IBOutlet UILabel *tcpReceiveMsg;
@property (weak, nonatomic) IBOutlet UITextField *portText;
@property (weak, nonatomic) IBOutlet UITextField *udpSendMsg;
@property (weak, nonatomic) IBOutlet UILabel *udpReceiveMsg;
@property (weak, nonatomic) IBOutlet UILabel *udpInfo;
@property (weak, nonatomic) IBOutlet UITextField *boardcastPort;

@property (weak, nonatomic) IBOutlet UIButton *broadcastReceiveButton;
@property (weak, nonatomic) IBOutlet UILabel *braodcastUDPKeyId;
@property (weak, nonatomic) IBOutlet UITextField *sendBroadcastPort;

- (IBAction)udpRecv:(id)sender;
@property (weak, nonatomic) IBOutlet UILabel *allHintMsg;
@property (weak, nonatomic) IBOutlet UIButton *udpRecvBtn;

@property(nonatomic)sstUdp *udpsend;
@property(nonatomic)sstUdp *udprecv;

@property(nonatomic)sstUdp *broadcast;
@property(nonatomic)sstUdp *sendbroadcast;

@property(nonatomic)sstTcp *tcp;
@property(nonatomic)BOOL isUdpOpen;
@property(nonatomic)BOOL isBroadCastOpen;
@property(nonatomic)BOOL isTcpConnect;

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSLog(@"Hello World!");
    NSLog(@"主线程---%@",[NSThread currentThread]);
    
    self.udpsend = [[sstUdp alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
    [self.udpsend setUdpErrorDelegate:self];
    [self.udpsend setUdpInfoNotifyDelegate: self];
    [self.udpsend enableReusePort: YES error: nil];
    
    self.udprecv = [[sstUdp alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
    [self.udprecv setUdpErrorDelegate:self];
    
    self.broadcast = [[sstUdp alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
    self.tcp = [[sstTcp alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
    [self.tcp setTcpErrorDelegate:self];
    [self.tcp setTcpInfoNotifyDelegate:self];
    
    [self.broadcast enableBroadcast:YES error:nil];
    if(errorTagEncode == nil){
        NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"ErrorTag" ofType:@"plist"];
        errorTagEncode = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
    }
    self.sendbroadcast = [[sstUdp alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
    [self.sendbroadcast enableBroadcast: YES error:nil];
    
 }

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

/**
 *  按钮事件，用作UDP消息的发送和接收
 *
 *  @param sender sender description
 */
- (IBAction)UdpSend:(id)sender
{
    NSString *textContent = [[self udpSendMsg] text];
    NSString *ip = [[self ipText] text];
    NSInteger port = [[[self portText] text] intValue];
    [self.udpsend closeAfterSending];
    //udp发送
    if (self.isUdpOpen) {
        [self.udpsend close];
        NSLog(@"Stopped Udp Echo server");
        self.isUdpOpen = NO;
    }
    [self.udpsend sendData:[sstNSStringFormat NSString2NSData:textContent] toHost:ip port:port withTimeout:12 tag:123456789];
    //udp接收绑定当前端口
}

-(void)udpSocket:(GCDAsyncUdpSocket *)sock didSendDataWithTag:(long)tag
{
    NSLog(@"didSendDataWithTag");
}

/**
 *  覆写sstUDP函数，UDP接收数据的回调函数
 *
 *  @param sock          sock description
 *  @param data          data description
 *  @param address       address description
 *  @param filterContext filterContext description
 */
- (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data fromAddress:(NSData *)address withFilterContext:(id)filterContext{
    NSString *receive = [sstNSDataFormat NSData2NSString:data];
    NSLog(@"UDP接收到的数据为：%@", receive);
    
    if(sock == self.broadcast)
        [[self braodcastUDPKeyId] setText:receive];
    else
        [[self udpReceiveMsg] setText:receive];
}

/**
 *  按钮事件，用作TCP建立连接使用
 *
 *  @param sender sender description
 */
- (IBAction)TcpConnect:(id)sender
{
    NSString *ip = [[self ipText] text];
    NSInteger port = [[[self tcpPort] text] intValue];
    if(self.isTcpConnect){
        self.isTcpConnect = NO;
        [self.tcp disconnect];
        [[self tcpReceiveMsg] setText:@"TCP Connection Stop!"];
        [self.tcpConnectButton setTitle:@"TCP建立连接" forState:UIControlStateNormal];
    }else{
        NSError *error = nil;
        if (![self.tcp connectToHost:ip onPort:port error:&error])
        {
            NSLog(@"Unable to connect to due to invalid configuration: %@", error);
            [self.allHintMsg setText:@"TCP连接建立失败"];
            self.isTcpConnect = NO;
            [self.tcpConnectButton setTitle:@"TCP建立连接" forState:UIControlStateNormal];
        }
        else
        {
            NSLog(@"Trying Connecting to %@ :%ld", ip, port);
            [self.allHintMsg setText:[NSString stringWithFormat:@"正在尝试向IP:\"%@\" Port:\"%ld\"建立连接", ip, port]];
        }
    }
}

/**
 *  覆写sstTCP函数，TCP建立连接成功后的回调函数
 *
 *  @param sock sock description
 *  @param host host description
 *  @param port port description
 */
-(void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port
{
    NSLog(@"socket:didConnectToHost:%@ port:%hu", host, port);
    [self.allHintMsg setText:@"TCP连接建立成功"];
    self.isTcpConnect = YES;
    [self.tcpConnectButton setTitle:@"TCP发送ing" forState:UIControlStateNormal];
    //建立TCP连接后，立马发送数据
    NSString * requestStr = @"1234567890abcdefghijklmnopqrstuvwxyz";
    
    //这里开一个异步的线程发送
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        // 处理耗时操作的代码块...
        while(self.isTcpConnect){
            //用来进行测试，每隔5s循环向家电端发送一次数据
            [self.tcp writeData:[sstNSStringFormat NSString2NSData:requestStr] withTimeout:-1 tag:0];
            [self.tcp readDataWithTimeout:1 tag:0];
            [NSThread sleepForTimeInterval: 10];
        }
        //        //通知主线程刷新
        //        dispatch_async(dispatch_get_main_queue(), ^{
        //            //回调或者说是通知主线程刷新，
        //        });
    });
}

// GCDAsyncSocket call back.
-(void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err
{
    self.isTcpConnect = NO;
    if ([NSThread isMainThread])
     {
         [[self tcpReceiveMsg] setText:@"TCP Connection Stop!"];
         [self.tcpConnectButton setTitle:@"TCP发送" forState:UIControlStateNormal];
     }
    else{
    dispatch_sync(dispatch_get_main_queue(), ^{
            [[self tcpReceiveMsg] setText:@"TCP Connection Stop!"];
            [self.tcpConnectButton setTitle:@"TCP发送" forState:UIControlStateNormal];
    });
    }
    [self updateHintMsg: @"TCP 断开"];
 }

// GCDAsyncSocket call back.
-(void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
    NSString* receive = [sstNSDataFormat NSData2NSString:data];
    NSLog(@"TCP接收到的数据为：%@", receive);
    [[self tcpReceiveMsg] setText:receive];
}

/**
 *  1、广播的接收
 *
 *  @param sender sender description
 */
- (IBAction)broadcastReceive:(id)sender
{
    NSInteger port = [[[self boardcastPort] text] intValue];
    if (self.isBroadCastOpen) {
        [self.broadcast close];
        NSLog(@"Stopped Broadcast Echo server");
        self.isBroadCastOpen = NO;
        [[self braodcastUDPKeyId] setText:@"BroadCast Stop!"];
        [self.broadcastReceiveButton setTitle:@"广播接收" forState:UIControlStateNormal];
        
    }else{
        NSError *error = nil;
        if(![self.broadcast bindToPort:port error:&error]){
            NSLog(@"%@", error);
            return;
        }
        if(![self.broadcast beginReceiving:&error]){
            [self.broadcast close];
            NSLog(@"%@", error);
            return;
        }
        NSLog(@"started Broadcast Echo server");
        self.isBroadCastOpen = YES;
        [self.broadcastReceiveButton setTitle:@"接收ing" forState:UIControlStateNormal];
    }
}

-(void)sstTcpError:(sstTcp *)tcp withTag:(NSInteger)tag
{
    NSString *errorMsg = [errorTagEncode objectForKey:[NSString stringWithFormat:@"%ld",(long)tag]];
    [self updateHintMsg: errorMsg];
    NSLog(@"%@", errorMsg);
}

-(void)sstInfoNotify:(sstUdp*)udp withInfo: (NSString *)info
{
    if ([NSThread isMainThread])
    {
        [self.udpInfo setText: info];
    }
    else{
        dispatch_sync(dispatch_get_main_queue(), ^{
            [self.udpInfo setText: info];
        });
    }
}

-(void)sstTcpInfoNotify:(sstTcp*)udp withInfo: (NSString *)info;
{
    if ([NSThread isMainThread])
    {
        [self.tcpInfo setText: info];
    }
    else{
        dispatch_sync(dispatch_get_main_queue(), ^{
            [self.tcpInfo setText: info];
        });
    }
}
-(void)sstUdpError:(sstUdp *)udp withTag:(NSInteger)tag
{
    NSString *errorMsg = [errorTagEncode objectForKey:[NSString stringWithFormat:@"%ld",(long)tag]];
    [self updateHintMsg: errorMsg];
    NSLog(@"%@", errorMsg);
}

-(void)updateHintMsg:(NSString *) msg
{
    if ([NSThread isMainThread])
    {
        [self.allHintMsg setText: msg];
    }
    else{
        dispatch_sync(dispatch_get_main_queue(), ^{
            [self.allHintMsg setText: msg];
        });
    }
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

- (IBAction)udpRecv:(id)sender
{
    NSLog(@"udpRecv port = %d", self.udpsend.port);
   if(self.udpsend.port == 0)
        return;
    
    [self.udprecv close];
    self.udpRecvBtn.enabled = false;
    NSError *error = nil;
    //if(![self.udprecv bindToPort: self.udpsend.localPort error:&error]){
    if(![self.udprecv bindToPort: 8000 error:&error])
    {
        NSLog(@"%@", error);
        return;
    }
    if(![self.udprecv beginReceiving:&error]){
        [self.udprecv close];
        NSLog(@"%@", error);
        return;
    }
    
    NSLog(@"started Udp Echo server at localPort: %d", self.udpsend.localPort);
    self.isUdpOpen = YES;
    self.udpRecvBtn.enabled = false;
}

- (IBAction)setWIFIwithSSID:(id)sender
{
    NSString* ssid = @"congruence";
    NSString* password = @"wwwbupt8";

    //先设置
    [SSTInitFactory setWIFIwithSSID:ssid withPassword:password];
    self.allHintMsg.text = @"设置SSID和密码成功";
}

- (IBAction)setDeviceInformation:(id)sender
{
    NSString* mac = @"0EBC327C4503";
    NSString* deviceId = @"87219347291619989379283472349237";
    NSString* ip = [[self ipText] text];
    [SSTInitFactory setDeviceInformation:deviceId withMac:mac withIP:ip];
    self.allHintMsg.text = @"设置家电信息成功";
}

- (IBAction)setSession:(id)sender
{
    NSString* deviceId = @"87219347291619989379283472349237";
    NSString* sessionId = @"u123hjk12hjkdhs12io3u12iouio";
    
    self.allHintMsg.text = @"设置session成功";
    [SSTInitFactory setSession:sessionId  withDeviceIDs: [NSArray arrayWithObject: deviceId]];
}

//发送广播消息
- (IBAction)sendBroadCast:(id)sender
{
    [self.sendbroadcast closeAfterSending];
   // [self.sendbroadcast sendData: [sstNSStringFormat NSString2NSData: @"broad cast to device"] toHost: @"255.255.255.255" port: [self.sendBroadcastPort.text intValue] withTimeout:12 tag:123456789];
    [self.sendbroadcast sendData:[sstNSStringFormat NSString2NSData: @"broad cast to device"] toHost:@"192.168.3.255" port:6335 withTimeout:-1 tag:0];
}

@end
